// pages/test2/test2.js
// pages/test/test.js

const db = wx.cloud.database()
const qnaire = require("./habit.js")  //导入题库
var ans = new Array(20)  //答案数组初始化，会在onload函数中赋初值""  
var sum=0
Page({
 /**第二种 */

data: {
 qnaire: qnaire.qnaire,
 answer: ans,
 //id: 19
 id:0
},

radioChange: function (e) {
 console.log(e.detail.value)
},

nextq: function () {
 if (this.data.id < 14) {   //<19
   this.setData({
     id: this.data.id + 1,
   })
 }
},

lastq: function (e) {
 if (this.data.id != 0) {
   this.setData({
     id: this.data.id - 1,
   })
 }
},

submit: function (e) {
 console.log(e.detail.value);
 var a = e.detail.value.answer;
 var id = this.data.id;
 ans[id] = a;
 /*for (var i in ans) {
  sum += Number(ans[i]);
}
 this.setData({
   answer: sum,
 })*/
 //console.log(this.data.answer);
 console.log(this.data.sum);

},

//判断答题完成情况
formSubmit: function() {
 var finish;
 var i = 0;
 var _this = this;
 while (i < 15) {     //i<20
   if (ans[i] == "") {
     finish = 'false';
     break;
   } else {
     finish = 'true';
   }
   i++;
 }
 if (finish == 'false') {
   wx.showModal({
     title: '无法提交',
     content: '您还有部分题目未完成，请检查后重新提交',
     showCancel: false,
     confirmColor: '#fcbe39',
     confirmText: "好的",
     success(res) {
       _this.setData({
         id: i,
       })
     }
   })
 } else {
   wx.showLoading({
     title: '加载中',
   })
   setTimeout(function () {
     wx.hideLoading({
       success(res) {
         _this.answer2db();
        /* wx.navigateBack({
           delta: 1
         })*/
         wx.redirectTo({
          url: '../result2/result2?sum='+sum,
        })
       }
     })
   }, 2000)
 }

 for (var i in ans) {
  sum += Number(ans[i]);
}
 this.setData({
   answer: sum,
 })
 console.log(this.data.sum);
},

//将用户完成的答案数组上传至云数据库
answer2db: function() {
 db.collection('score').add({
   data: {
     answer: this.data.answer
   },
   success(res) {
     console.log(res._id);
   },
   fail(res) {
     wx.showToast({
       icon: 'none',
       title: '新增记录失败'
     })
     console.error('[数据库] [新增记录] 失败：', err)
   }
 })
},
stopTouchMove: function(res){
  return false;
}

});